class AModelBanana

  attr_reader :type, :controller, :source, :description, :fields, :fieldtypes, :constraints
  
  def initialize store
    raise AModelBananaException, 'Did not receive APersistentBanana' unless store.kind_of? APersistentBanana
    @store = store
  end
  
  def load key_array, blind = false
    key = key_array.join('/')
    begin
      @type = blind ? key : @store.get_value(key)
      @controller = @store.get_value("/model/#{@type}").to_sym
      @source = @store.get_value "/model/#{@type}/source"
      @description = @store.get_value "/model/#{@type}/description"
      load_fields
    rescue APersistentBananaException
      raise AModelBananaException, "The key #{key} does not represent a registered object."
    end
  end
  
 
  private
  
  def load_fields
    spec = @store.get_full_model(@type)
    # TODO: data-checking
    # TODO: apply ordering if present
    @fields = []
    @fieldtypes = {}
    @constraints = {}
    regex = /\/model\/#{Regexp.quote(@type)}\/([^\/]+)\/.+/
    spec.each do |row|
      field = row['key'].scan(regex)
      @fields.push field[0][0] if field.count > 0
    end
    @fields.uniq!
    @fields.each do |field|
      # TODO: data-checking
      @fieldtypes[field] = @store.get_value("/model/#{@type}/#{field}/type")
      begin
        @constraints[field] = @store.get_value("/model/#{@type}/#{field}/constraint")
      rescue
        # no problem, these are not mandatory
      end
    end
  end
  
end